package frame;

import pojo.UserDO;
import service.UserService;
import service.impl.UserServiceImpl;
import util.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginPanel extends JPanel implements ActionListener {
    private ATM atm;
    private JButton loginBtn;
    private JButton offBtn;
    private Icon loginImg = Util.getImageIcon("/images/buttonLand.jpg");
    private Icon offImg = Util.getImageIcon("/images/buttonOff.jpg");
    private int errorcount = 3;

    private JTextField inputname = new JTextField();
    private JPasswordField inputpsw = new JPasswordField();

    private UserService userService = new UserServiceImpl();

    public LoginPanel(ATM atm) {
        this.atm = atm;
        this.setLayout(null);
        this.setOpaque(false);

        //账号
        JLabel username = new JLabel("用户名");
        username.setBounds(220, 200, 130, 30);
        username.setFont(new Font("黑体", Font.BOLD, 16));
        this.add(username);

        inputname.setBounds(370, 200, 130, 30);
        this.add(inputname);

        //密码
        JLabel pswname = new JLabel("密码");
        pswname.setBounds(220, 240, 130, 30);
        pswname.setFont(new Font("黑体", Font.BOLD, 16));
        this.add(pswname);

        inputpsw.setBounds(370, 240, 130, 30);
        this.add(inputpsw);


        //登录按钮
        loginBtn = new JButton(loginImg);
        loginBtn.setBounds(250, 400, 140, 50);
        this.add(loginBtn);
        loginBtn.addActionListener(this);

        offBtn = new JButton(offImg);
        offBtn.setBounds(410, 400, 140, 50);
        this.add(offBtn);
        offBtn.addActionListener(this);
    }


    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == loginBtn) {
//            for (int i = 0; i < atm.getUsers().size(); i++) {
//                if (inputname.getText().equals(atm.getUsers().get(i).getUsername()) && inputpsw.getText().equals(atm.getUsers().get(i).getPassword())) {
//                    atm.setNum(i);
//                    inputname.setText("");
//                    inputpsw.setText("");
//                    atm.switchPanel("menu");
//                    return;
//                }
//            }

//            Util db = new Util();
            UserDO user = userService.getByUsernameAndPsw(inputname.getText(), inputpsw.getText());
            if (user != null) {
                atm.setLoginUser(user);
                atm.switchPanel("menu");
                return;
            }
            errorcount--;
            if (errorcount == 0) {
                JOptionPane.showMessageDialog(this, "吞卡");
                System.exit(0);
            }
        } else if (e.getSource() == offBtn) {
            System.exit(0);
        }
        JOptionPane.showMessageDialog(this, "登陆失败,还剩" + errorcount + "次机会");

    }
}

